package com.example.backendhjh.service;

import com.example.backendhjh.dto.LoginDTO;
import com.example.backendhjh.dto.UserDTO;
import com.example.backendhjh.dto.UserResponseDTO;
import com.example.backendhjh.entity.User;
import com.example.backendhjh.exception.ApiException;
import com.example.backendhjh.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class UserService {

    private final UserMapper userMapper;

    @Autowired
    public UserService(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    @Transactional
    public UserResponseDTO registerUser(UserDTO userDTO) {
        // 检查用户名是否已存在
        User existingUser = userMapper.findByUsername(userDTO.getUsername());
        if (existingUser != null) {
            throw new ApiException(HttpStatus.CONFLICT, "用户名已被使用");
        }

        // 创建用户实体
        User user = new User();
        user.setUsername(userDTO.getUsername());
        user.setPassword(userDTO.getPassword());
        user.setEmail(userDTO.getEmail());
        user.setRole(userDTO.getRole() != null ? userDTO.getRole() : "BUYER");
        user.setCreatedAt(LocalDateTime.now());

        try {
            // 插入用户
            int result = userMapper.insert(user);
            if (result <= 0) {
                throw new ApiException(HttpStatus.INTERNAL_SERVER_ERROR, "用户注册失败");
            }
        } catch (DuplicateKeyException e) {
            throw new ApiException(HttpStatus.CONFLICT, "邮箱已被使用");
        }

        return convertToResponseDTO(user);
    }

    public UserResponseDTO loginUser(LoginDTO loginDTO) {
        // 根据用户名查找用户
        User user = userMapper.findByUsername(loginDTO.getUsername());
        if (user == null) {
            throw new ApiException(HttpStatus.UNAUTHORIZED, "用户名或密码错误");
        }

        // 验证密码
        if (!user.getPassword().equals(loginDTO.getPassword())) {
            throw new ApiException(HttpStatus.UNAUTHORIZED, "用户名或密码错误");
        }

        return convertToResponseDTO(user);
    }

    public UserResponseDTO getUserById(Long id) {
        User user = userMapper.findById(id);
        if (user == null) {
            throw new ApiException(HttpStatus.NOT_FOUND, "用户不存在");
        }
        return convertToResponseDTO(user);
    }

    public List<UserResponseDTO> getAllUsers() {
        List<User> users = userMapper.findAll();
        return users.stream()
                .map(this::convertToResponseDTO)
                .collect(Collectors.toList());
    }

    @Transactional
    public UserResponseDTO updateUser(Long id, UserDTO userDTO) {
        // 检查用户是否存在
        User existingUser = userMapper.findById(id);
        if (existingUser == null) {
            throw new ApiException(HttpStatus.NOT_FOUND, "用户不存在");
        }

        // 更新用户信息
        if (userDTO.getUsername() != null) {
            existingUser.setUsername(userDTO.getUsername());
        }
        if (userDTO.getPassword() != null) {
            existingUser.setPassword(userDTO.getPassword());
        }
        if (userDTO.getEmail() != null) {
            existingUser.setEmail(userDTO.getEmail());
        }
        if (userDTO.getRole() != null) {
            existingUser.setRole(userDTO.getRole());
        }

        // 执行更新
        int result = userMapper.update(existingUser);
        if (result <= 0) {
            throw new ApiException(HttpStatus.INTERNAL_SERVER_ERROR, "用户更新失败");
        }

        return convertToResponseDTO(existingUser);
    }

    @Transactional
    public void deleteUser(Long id) {
        User user = userMapper.findById(id);
        if (user == null) {
            throw new ApiException(HttpStatus.NOT_FOUND, "用户不存在");
        }

        int result = userMapper.delete(id);
        if (result <= 0) {
            throw new ApiException(HttpStatus.INTERNAL_SERVER_ERROR, "用户删除失败");
        }
    }

    private UserResponseDTO convertToResponseDTO(User user) {
        UserResponseDTO dto = new UserResponseDTO();
        dto.setId(user.getId());
        dto.setUsername(user.getUsername());
        dto.setEmail(user.getEmail());
        dto.setRole(user.getRole());
        dto.setCreatedAt(user.getCreatedAt());
        return dto;
    }
}